package com.zzyl.nursing.service.impl;
import java.util.Date;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.dto.DevicesUpdateDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Arrays;
/**
 * 设备管理Service业务层处理
 * 
 * @author Winnie
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device)?1:0;
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device)?1:0;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private IoTDAClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;


    //同步产品列表
    @Override
    public void syncProductList() {

        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        List<ProductSummary> products = response.getProducts();

        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String s = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        if (s!=null) {
            List<ProductVo> productVos = JSONUtil.toList(s, ProductVo.class);
            return productVos;
        }
        return List.of();
    }

    @Override
    public void registerDevice(DeviceDto dto) {
        // 查询设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName,dto.getDeviceName());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("设备名称重复");
        }

        // 查询设备标识是否重复
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getNodeId,dto.getNodeId());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("设备标识重复");
        }

        // 查询同一个位置是否绑定了相同的产品
        //设备类型   具体位置  productKey
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getLocationType,dto.getLocationType());
        queryWrapper.eq(Device::getBindingLocation,dto.getBindingLocation());
        queryWrapper.eq(Device::getProductKey,dto.getProductKey());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("同一个位置绑定了相同的产品");
        }


        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(dto.getNodeId());
        body.setDeviceName(dto.getDeviceName());
        body.setProductId(dto.getProductKey());
        AuthInfo authInfo = new AuthInfo(); //秘钥
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret); //秘钥
        body.setAuthInfo(authInfo);
        body.setDescription(dto.getDeviceDescription());
        request.setBody(body);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode()!=201) {
            throw new BaseException("IOT设备添加失败");
        }
        String deviceId = response.getDeviceId();

        // 本地存储设备
        Device device = BeanUtil.toBean(dto, Device.class);
        // device.setId(0L);
        device.setIotId(deviceId);
        device.setSecret(secret);

        this.save(device);
    }

    @Override
    public DeviceDetailVo deviceDetail(String iotId) {
        // IOT查询
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT设备查询失败");
        }
        // 本地查询
        Device device = this.getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId,iotId));
        if (device==null) {
            throw new BaseException("设备不存在");
        }

        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        //设备状态
        deviceDetailVo.setDeviceStatus(response.getStatus());

        String activeTimeStr = response.getActiveTime();
        LocalDateTime activeTime = null;

// 1. 先校验activeTimeStr是否为null或空字符串，避免解析null
        if (activeTimeStr != null && !activeTimeStr.trim().isEmpty()) {
            try {
                // 2. 解析时捕获可能的格式异常（如字符串格式不匹配UTC_MS_PATTERN）
                LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
                // 3. 校验解析结果是否为null，再调用时区转换
                if (parse != null) {
                    activeTime = DateTimeZoneConverter.utcToShanghai(parse);
                }
            } catch (Exception e) {
                throw new BaseException("解析设备活跃时间失败，时间字符串：{}", activeTimeStr);
            }
        }

        deviceDetailVo.setActiveTime(activeTime);

        return deviceDetailVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        List<DeviceDataVo> list = new ArrayList<>();

        // IOT查询数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT设备查询失败");
        }

        List<DeviceShadowData> shadowList = response.getShadow();
        if(CollUtil.isNotEmpty(shadowList)){

            DeviceShadowData deviceShadowData = shadowList.get(0);
            DeviceShadowProperties reported = deviceShadowData.getReported();
            String eventTimeStr = reported.getEventTime();
            LocalDateTime eventTimeUTC = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeUTC);

            Object properties = reported.getProperties();
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            jsonObject.forEach((key,value)->{
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                deviceDataVo.setFunctionId(key);
                deviceDataVo.setEventTime(eventTime);
                deviceDataVo.setValue(value);
                list.add(deviceDataVo);
            });
        }
        return list;
    }


    @Override
    public void updateDevices(DevicesUpdateDto dto) {

        //修改本地

        Device device = this.getById(dto.getId());
        if(device==null){
            throw new BaseException("设备Id不存在");
        }
        device.setBindingLocation(dto.getBindingLocation());
        device.setLocationType(dto.getLocationType());
        device.setPhysicalLocationType(dto.getPhysicalLocationType());
        device.setDeviceName(dto.getDeviceName());
        device.setProductKey(dto.getProductKey());
        device.setProductName(dto.getProductName());
        device.setDeviceDescription(dto.getDeviceDescription());
        //device.setHaveEntranceGuard();
        device.setNodeId(dto.getNodeId());
        device.setRemark(dto.getRemark());

        this.updateById(device);

        String iotId = device.getIotId();
        if(iotId==null ||iotId.isEmpty() ){
            throw new BaseException("设备在 IoT 平台中的 iotId 为空，无法更新");
        }
        //修改IOT
        try {
            UpdateDeviceRequest request = new UpdateDeviceRequest();
            request.setDeviceId(iotId);
            UpdateDevice body = new UpdateDevice();
            AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
            authInfobody.withSecureAccess(true);
            body.withDeviceName(dto.getDeviceName());
            body.withDescription(dto.getDeviceDescription());
            // body.withExtensionInfo();
            body.withAuthInfo(authInfobody);
            request.withBody(body);
            UpdateDeviceResponse response = client.updateDevice(request);
            if (response.getHttpStatusCode() != 200){
                throw new BaseException("调用 IoT 平台失败，HTTP 状态码: \" + response.getHttpStatusCode()");
            }
        } catch (BaseException e) {
            throw new RuntimeException("设备远程更新失败：" + e.getMessage());
        }


    }

    @Override
    public void deleteDevices(String iotId) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId, iotId);
        Device device = this.getOne(queryWrapper);
        if (device!=null){
            this.removeById(device.getId());
        }

        try {
            DeleteDeviceRequest request = new DeleteDeviceRequest();
            request.setDeviceId(iotId);
            DeleteDeviceResponse response = client.deleteDevice(request);

            if (response.getHttpStatusCode() != 200){
                throw new BaseException("调用 IoT 平台失败，HTTP 状态码: \" + response.getHttpStatusCode()");
            }
        } catch (Exception e) {

        }

    }

    @Override
    public AjaxResult queryProduct(String productKey) {
//        ShowProductRequest request = new ShowProductRequest();
//        request.setProductId(productKey);
//        client.

            ShowProductRequest request = new ShowProductRequest();
            request.setProductId(productKey);
            ShowProductResponse response = client.showProduct(request);
            if (response.getHttpStatusCode()!=200){
                throw new BaseException("IOT查询失败");
            }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
            return AjaxResult.success(serviceCapabilities) ;


    }

}
